import React, { Component } from 'react';
import _ from 'underscore';
import cx from 'classnames';

export default class Single extends Component {
  constructor(props, context){
    super(props, context);
    this.state = {
      cols: this.resetColumns(props),
      dateSortOrientation: -1,
      currentSort: null,
      currentSortOrientation: -1
    }; // state
  } // constructor

  componentWillReceiveProps(nextProps) {
    this.setState({
      cols: this.resetColumns(nextProps)
    });
  } // componentWillReceiveProps

  resetColumns(props) {
    return _.map(props.cols, col => _.defaults(col, {
      title: '',
      className: '',
      sortable: false
    }));
  } // resetColumns

  sortHandler(column, index) {
      column.sort.call(this, column, index);
  } // sortHandler

  existSubpage(column) {
    let identity = '.unique'
      , index = column.key.indexOf(identity);

    return (identity.length + index) === column.key.length;
  } // existSubpage

  subpageHandler(item) {
    if (this.props.onClick) {
      this.props.onClick(condition => {
        let event = item[1].key.split('.')[1];
        condition.measures = _.filter(condition.measures, p => p.event_name === event && p.aggregator === 'unique');
        condition.slice_date = item[0].date;
        condition.slice_by_values = item[0].by_values;
        return condition;
      });
    }
  } // subpageHandler

  renderTableHeaderCell(column, index) {
    return (
      <th key={ `${ column.key }-${ index }` } className="sortedth" onClick={ this.sortHandler.bind(this, column, index) }>
        <span className="sortedtext">
          { column.title }
        </span>
        <span className={ cx(column.className, 'sorted-arrow', {
          'desc': this.state.currentSort === column.key && this.state.currentSortOrientation === -1,
          'asc': this.state.currentSort === column.key && this.state.currentSortOrientation === 1
        }) } />
      </th>
    );
  } // renderTableHeaderCell

  renderTableHeader() {
    let defaultColumn = this.state.cols[0];
    return (
      <thead>
        <tr>
          <th
            key="date"
            className="sortedth col-date"
            onClick={ this.sortHandler.bind(this, defaultColumn, 0) }>
            <span className="sortedtext">
              { defaultColumn.title }
            </span>
            <span className={ cx(defaultColumn.className, 'sorted-arrow', {
              'desc': this.state.dateSortOrientation === -1,
              'asc': this.state.dateSortOrientation === 1
            }) } />
          </th>
          {
            _.chain(this.state.cols).filter((p, i) => i !== 0).map(this.renderTableHeaderCell, this).value()
          }
        </tr>
      </thead>
    );
  } // renderTableHeader

  renderTableBody(data) {
    let rowGenerator = rowValue => _.map(rowValue, (item, i) => {
      if (typeof item[0] === 'string') {
        return (
          <td key={ item[1].key }>
            { item[0] }
          </td>
        );
      } else {
        let content = (<div>{ item[0].value === null ? '--' : item[0].value }</div>);
        if (this.existSubpage(item[1]) && item[0].value && item[0].value !== '--') {
          content = (
            <a
              data-tip="查看详细用户列表"
              onClick={ this.subpageHandler.bind(this, item) }
              style={{
                display: 'inline-block',
                cursor: 'pointer'
              }}>
              { item[0].value }
            </a>
          );
        }

        return (
          <td key={ item[1].key }>
            {
              item[0].value !== undefined ? content : null
            }
            <div className={ cx('ratio', {
              'ratio-neg': item[0].percentValue < 0,
              'ratio-pos': item[0].percentValue >= 0
            })}>{ item[0].percent }</div>
          </td>
        );
      }
    });

    return (
      <tbody>
        {
          !this.props.sum ? null : _.map(this.props.sum, row => (
            <tr key="total">
              <td key="date" className="col-date">合计</td>
              {
                rowGenerator(_.filter(_.zip(row.value[0], this.state.cols), (p, i) => i !== 0))
              }
            </tr>
          ))
        }
        {
          _.map(data, (row, index) => {
            return (
              <tr key={ row.key }>
                <td key="date" className="col-date">
                  { row.key }
                </td>
                {
                  rowGenerator(_.filter(_.zip(row.value[0], this.state.cols), (p, i) => i !== 0))
                }
              </tr>
            )
          })
        }
      </tbody>
    );
  } // renderTableBody

  render() {
    return (
      <div style={{
        whiteSpace: 'nowrap',
        overflowX: 'auto',
        overflowY: 'hidden'
      }}>
        <table className="table table-striped event-table">
          { this.renderTableHeader() }
          { this.renderTableBody(this.props.data) }
        </table>
      </div>
    );
  } // render
}

Single.defaultProps = {
  cols: [],
  data: [],
  onClick: null
}
